package org.example.myleet.learn.fontTest;

import javax.swing.*;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;

public class FontComponent extends JComponent {

    private static final int DEFAULT_WIDTH = 600;
    private static final int DEFAULT_HEIGHT = 400;

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        String msg = "Hello, world!";
        Font font = new Font("Serif", Font.BOLD, 36);
        g2.setFont(font);

        //measure the size of message
        FontRenderContext context = g2.getFontRenderContext();
        Rectangle2D bound = font.getStringBounds(msg, context);

        //get the top-left conner of the message's bound
        double x = (getWidth() - bound.getWidth()) / 2;
        double y = (getHeight() - bound.getHeight()) / 2;

        //add ascent to y to reach the baseline
        double ascent = -bound.getY();
        double baseY = y + ascent;

        //draw the message
        g2.drawString(msg, (int) x, (int) baseY);

        //draw the baseline
        Line2D baseline = new Line2D.Double(x, baseY, x + bound.getWidth(), baseY);
        g2.setColor(Color.RED);
        g2.draw(baseline);

        //draw the enclosing rectangle
        Rectangle2D rect = new Rectangle2D.Double(x, y, bound.getWidth(), bound.getHeight());
        g2.setColor(Color.BLUE);
        g2.draw(rect);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
//        Toolkit toolkit = Toolkit.getDefaultToolkit();
//        Dimension screenSize = toolkit.getScreenSize();
//        int screenHeight = screenSize.height;
//        int screenWidth = screenSize.width;
//        return new Dimension(screenWidth / 2, screenHeight / 2);
    }
}
